package com.zym.init.configuration;

import com.zym.init.async.TraceTaskDecorator;
import com.zym.init.filter.TraceFilter;
import com.zym.init.log.RequestLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.task.TaskDecorator;
import org.springframework.web.filter.GenericFilterBean;

/**
 * traceId自动配置
 *
 * @author ZouYangMing
 */
@Configuration
public class TraceConfiguration {

    /**
     * 异步任务装饰器
     *
     * @return TaskDecorator
     */
    @Bean
    @ConditionalOnMissingBean
    public TaskDecorator taskDecorator() {
        return new TraceTaskDecorator();
    }

    /**
     * 过滤器注册
     */
    @ConditionalOnClass({FilterRegistrationBean.class, GenericFilterBean.class})
    @Configuration
    static class FilterRegistrationConfig {
        @Bean
        @ConditionalOnMissingBean(name = "traceFilter")
        public FilterRegistrationBean<TraceFilter> traceFilter() {
            FilterRegistrationBean<TraceFilter> registration = new FilterRegistrationBean<>();
            registration.setFilter(new TraceFilter());
            registration.addUrlPatterns("/*");
            registration.setName("traceFilter");
            registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
            return registration;
        }
    }

    /**
     * 切面配置
     */
    @ConditionalOnClass(ProceedingJoinPoint.class)
    @Configuration
    static class AspectjAopConfig {
        @Bean
        public RequestLog requestLog() {
            return new RequestLog();
        }
    }
}
